<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
import type { FileClientConfig, FileConfig } from '@/service/api';
import { createFileConfig, updateFileConfig } from '@/service/api';
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict';

defineOptions({
  name: 'FileConfigOperateModel'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: FileConfig | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const submitLoading = ref(false);

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: $t('page.base.file.config.addFileConfig'),
    edit: $t('page.base.file.config.editFileConfig')
  };
  return titles[props.operateType];
});

type Model = Pick<FileConfig, 'id' | 'name' | 'config' | 'remark' | 'storage' | 'master'> & {
  domain: string;
};

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    id: 0,
    name: '',
    config: {} as FileClientConfig,
    remark: '',
    storage: null,
    master: false,
    domain: ''
  };
}

type RuleKey = Extract<keyof Model, 'name' | 'storage'> & {
  config: {
    basePath: string;
    host: string;
    port: string;
    username: string;
    password: string;
    mode: string;
    endpoint: string;
    bucket: string;
    accessKey: string;
    accessSecret: string;
    domain: string;
  };
};

const rules: Record<RuleKey, App.Global.FormRule> = {
  name: defaultRequiredRule,
  storage: defaultRequiredRule,
  config: {
    basePath: defaultRequiredRule,
    host: defaultRequiredRule,
    port: defaultRequiredRule,
    username: defaultRequiredRule,
    password: defaultRequiredRule,
    mode: defaultRequiredRule,
    endpoint: defaultRequiredRule,
    bucket: defaultRequiredRule,
    accessKey: defaultRequiredRule,
    accessSecret: defaultRequiredRule,
    domain: defaultRequiredRule
  }
};

const modeOptions = [
  {
    value: 'Active',
    label: $t('page.base.file.config.modeActive')
  },
  {
    value: 'Passive',
    label: $t('page.base.file.config.modePassive')
  }
];

function handleInitModel() {
  Object.assign(model, createDefaultModel());

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
  }
}

function closeDrawer() {
  submitLoading.value = false;
  visible.value = false;
}

async function handleSubmit() {
  await validate();

  submitLoading.value = true;

  if (props.operateType === 'edit') {
    const { error } = await updateFileConfig(model.id, model);

    if (!error) {
      window.$message?.success($t('common.updateSuccess'));
      closeDrawer();
      emit('submitted');
    }
  } else {
    const { error } = await createFileConfig(model);
    if (!error) {
      window.$message?.success($t('common.addSuccess'));
      closeDrawer();
      emit('submitted');
    }
  }
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
  }
});
</script>

<template>
  <NModal v-model:show="visible" :title="title" preset="card" class="w-200">
    <NScrollbar class="max-h-200 pr-20px">
      <NForm ref="formRef" :model="model" :rules="rules" label-placement="left" label-width="120px">
        <NFormItem :label="$t('page.base.file.config.name')" path="name">
          <NInput v-model:value="model.name" :placeholder="$t('page.base.file.config.form.name')" />
        </NFormItem>
        <NFormItem :label="$t('page.base.file.config.remark')" path="remark">
          <NInput v-model:value="model.remark" :placeholder="$t('page.base.file.config.form.remark')" />
        </NFormItem>
        <NFormItem :label="$t('page.base.file.config.storage')" path="storage">
          <NSelect
            v-model:value="model.storage"
            :disabled="model.id !== 0"
            :placeholder="$t('page.base.file.config.form.storage')"
            :options="getStrDictOptions(DICT_TYPE.SYSTEM_FILE_STORAGE)"
            clearable
          />
        </NFormItem>
        <!-- DB -->
        <!-- Local / FTP / SFTP -->
        <NFormItem
          v-if="model.storage === 'LOCAL' || model.storage === 'FTP' || model.storage === 'SFTP'"
          :label="$t('page.base.file.config.basePath')"
          path="config.basePath"
        >
          <NInput v-model:value="model.config.basePath" :placeholder="$t('page.base.file.config.form.basePath')" />
        </NFormItem>
        <NFormItem
          v-if="model.storage === 'FTP' || model.storage === 'SFTP'"
          :label="$t('page.base.file.config.host')"
          path="config.host"
        >
          <NInput v-model:value="model.config.host" :placeholder="$t('page.base.file.config.form.host')" />
        </NFormItem>
        <NFormItem
          v-if="model.storage === 'FTP' || model.storage === 'SFTP'"
          :label="$t('page.base.file.config.port')"
          path="config.port"
        >
          <NInputNumber v-model:value="model.config.port" :placeholder="$t('page.base.file.config.form.port')" />
        </NFormItem>
        <NFormItem
          v-if="model.storage === 'FTP' || model.storage === 'SFTP'"
          :label="$t('page.base.file.config.username')"
          path="config.username"
        >
          <NInput v-model:value="model.config.username" :placeholder="$t('page.base.file.config.form.username')" />
        </NFormItem>
        <NFormItem
          v-if="model.storage === 'FTP' || model.storage === 'SFTP'"
          :label="$t('page.base.file.config.password')"
          path="config.password"
        >
          <NInput v-model:value="model.config.password" :placeholder="$t('page.base.file.config.form.password')" />
        </NFormItem>
        <NFormItem v-if="model.storage === 'FTP'" :label="$t('page.base.file.config.mode')" path="config.mode">
          <NRadioGroup v-model:value="model.config.mode">
            <NRadio
              v-for="item in modeOptions"
              :key="item.value"
              :value="item.value"
              :label="item.label"
              :placeholder="$t('page.base.file.config.form.mode')"
            />
          </NRadioGroup>
        </NFormItem>
        <!-- S3 -->
        <NFormItem v-if="model.storage === 'S3'" :label="$t('page.base.file.config.endpoint')" path="config.endpoint">
          <NInput v-model:value="model.config.endpoint" :placeholder="$t('page.base.file.config.form.endpoint')" />
        </NFormItem>
        <NFormItem v-if="model.storage === 'S3'" :label="$t('page.base.file.config.bucket')" path="config.bucket">
          <NInput v-model:value="model.config.bucket" :placeholder="$t('page.base.file.config.form.bucket')" />
        </NFormItem>
        <NFormItem v-if="model.storage === 'S3'" :label="$t('page.base.file.config.accessKey')" path="config.accessKey">
          <NInput v-model:value="model.config.accessKey" :placeholder="$t('page.base.file.config.form.accessKey')" />
        </NFormItem>
        <NFormItem
          v-if="model.storage === 'S3'"
          :label="$t('page.base.file.config.accessSecret')"
          path="config.accessSecret"
        >
          <NInput
            v-model:value="model.config.accessSecret"
            :placeholder="$t('page.base.file.config.form.accessSecret')"
          />
        </NFormItem>
        <!-- 通用 -->
        <NFormItem v-if="model.storage === 'S3'" :label="$t('page.base.file.config.domain')">
          <!-- 无需参数校验，所以去掉 path -->
          <NInput v-model:value="model.config.domain" :placeholder="$t('page.base.file.config.form.domain')" />
        </NFormItem>
        <NFormItem v-else-if="model.storage" :label="$t('page.base.file.config.domain')" path="config.domain">
          <NInput v-model:value="model.config.domain" :placeholder="$t('page.base.file.config.form.domain')" />
        </NFormItem>
      </NForm>
    </NScrollbar>
    <template #footer>
      <NSpace justify="end" :size="16">
        <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
        <NButton type="primary" :loading="submitLoading" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
